﻿using Owin;
using System.Net.Http.Formatting;
using System.Web.Http;
using WebApiThrottle;

namespace ldhWebApi
{
    public class WebApi
    {
        // This code configures Web API. The Startup class is specified as a type
        // parameter in the WebApp.Start method.
        public void Configuration(IAppBuilder appBuilder)
        {
            // Configure Web API for self-host. 
            HttpConfiguration config = new HttpConfiguration();
            config.EnableCors();

            // Web API routes
            config.MapHttpAttributeRoutes();

            //config.Routes.MapHttpRoute(
            //    name: "DefaultApi",
            //    routeTemplate: "api/{controller}/{id}",
            //    defaults: new { action = "DefaultAction", id = RouteParameter.Optional }
            //);
            var jsonFormatter = new JsonMediaTypeFormatter();
            config.Services.Replace(typeof(IContentNegotiator), new JsonContentNegotiator(jsonFormatter));

            //访问时间限制 限制生效后返回429
            config.MessageHandlers.Add(new ThrottlingHandler()
            {
                Policy = new ThrottlePolicy(perSecond: 2)
                {
                    IpThrottling = true
                },
                Repository = new MemoryCacheRepository()
            });

            //验证身份
            //appBuilder.Use(typeof(CheckUkeyMiddleware));

            appBuilder.UseWebApi(config);
        }
    }
}
